import React, { useEffect, useState } from "react";
import { useRequest, useSetState } from "ahooks";
import { userQuery, userDelById, userAdd } from "../service/userService";

export default function UseRequest() {
  const [username, setUsername] = useState("");
  const [userage, setUserage] = useState("");
  const [list, setList] = useState([]);

  const [info, setinfo] = useSetState({
    username: "leson",
    userage: 18,
  });

  //页面加载的方法
  let { run: GetList } = useRequest(userQuery, {
    manual: true, //手动触发
    debounceWait: 500, //表示两秒内只触发一次
    onSuccess: (res) => {
      setList(res.data);
    },
  });
  useEffect(() => {
    GetList({}); //页面加载  触发
  }, []);

  //删除的方法
  let { run: delListById } = useRequest(userDelById, {
    manual: true, //表示手动触发
    throttleWait: 3000, //节流

    onSuccess: (res, params) => {
      //     console.log(params);
      //   GetList({}); //获取最新的数据
      setList(list.filter((item) => item.id !== params[0]));
    },
  });

  //新增的方法
  let { run: addList } = useRequest(userAdd, {
    manual: true, //表示手动触发
    throttleWait: 1000, //节流
    onSuccess: (res, params) => {
      //     console.log(res.data);
      //     console.log(params);
      //   GetList({}); //获取最新的数据
      setList([...list, res.data]);
    },
  });

  return (
    <div>
      <div>
        姓名{" "}
        <input
          value={username}
          onChange={(e) => {
            setUsername(e.target.value);
          }}
        />{" "}
      </div>
      <div>
        年龄{" "}
        <input
          value={userage}
          onChange={(e) => {
            setUserage(e.target.value);
          }}
        />{" "}
      </div>
      <button
        onClick={() => {
          addList({ username, userage });
        }}
      >
        新增
      </button>
      <hr />
      <input
        placeholder="用户名查询"
        onChange={(e) => {
          GetList({ username_like: e.target.value }); //表示根据用户名进行查询
        }}
      />
      <div className="tr">
        <div className="td">编号</div>
        <div className="td">姓名</div>
        <div className="td">年龄</div>
        <div className="td">操作</div>
      </div>

      {list.map((item) => {
        return (
          <div className="tr" key={item.id}>
            <div className="td">{item.id}</div>
            <div className="td">{item.username}</div>
            <div className="td">{item.userage}</div>
            <div
              className="td"
              onClick={() => {
                delListById(item.id);
              }}
            >
              删除
            </div>
          </div>
        );
      })}

      <div>
        对象的更新 姓名{info.username} 年龄{info.userage}
        <button
          onClick={() => {
            setinfo({ userage: 100 });
          }}
        >
          更新
        </button>
      </div>
    </div>
  );
}
